<template>
  <div>
    <a-card :bordered="false" style="position: relative; margin-bottom: 10px">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper" style="position: relative">
        <div class="search-wrapper-btn">
          <a-button type="link" @click="show = !show">
            <span v-if="!show">展开<a-icon type="down" /></span>
            <span v-else>收起<a-icon type="up" /></span>
          </a-button>
        </div>
        <a-form-model :label-col="labelCol" :wrapper-col="wrapperCol" @keyup.enter.native="onQuery">
          <div class="mode_item mode_item_none">
            <a-form-model-item label="更新时间" class="zdy-form-item-label">
              <a-radio-group buttonStyle="solid" v-model="formData.timeType">
                <a-radio-button v-for="(item, key) in options" :key="key" :value="item.value">
                  {{ item.text }}
                </a-radio-button>
              </a-radio-group>
              <a-range-picker
                v-if="formData.timeType === '0'"
                :allowClear="true"
                v-model="rangePickerTime"
                valueFormat="YYYY-MM-DD"
                @change="rangePickerChange"
                style="margin-left: 10px"
              />
            </a-form-model-item>
          </div>
          <div class="mode_item mode_item_none" v-show="show">
            <a-form-model-item label="数据来源" class="zdy-form-item-label">
              <a-checkbox
                :indeterminate="indeterminateState"
                :checked="checkAllState"
                @change="onCheckAllChange($event)"
              >
                全部
              </a-checkbox>
              <j-multi-select-tag
                v-model="formData.sourceTypeList"
                dictCode="dataSource"
                type="checkbox"
                @change="onChange($event)"
              />
            </a-form-model-item>
          </div>
          <div class="mode_item" v-show="show">
            <a-form-model-item label="账户名" class="zdy-form-item-label">
              <a-input v-model="formData.userName" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item label="疑似走私发布数">
              <j-dict-select-tag v-model="formData.publishedType" placeholder="请选择" dictCode="publishedType" />
            </a-form-model-item>
          </div>
          <div style="margin-top: 20px">
            <a-form-model-item :wrapper-col="{ offset: 0 }" style="margin-bottom: 0">
              <a-button class="Indormation-list-CX" type="primary" @click="onQuery"> 查询 </a-button>
              <a-button class="Indormation-list-CX" style="margin-left: 10px" @click="onResetForm"> 重置 </a-button>
              <span>
                <a-button type="primary" style="margin: 0 10px" @click="saveConfig"> 保存配置 </a-button>
                <!-- <a-tooltip placement="leftTop">
                  <template slot="title">
                    <span>针对预警时间、劝阻状态、预警等级、处置方式的当前选择保存配置</span>
                  </template>
                  <a-icon type="question-circle" />
                </a-tooltip> -->
              </span>
            </a-form-model-item>
          </div>
        </a-form-model>
      </div>
    </a-card>
    <a-card :bordered="false">
      <!-- 操作按钮区域 -->
      <div style="margin-bottom: 20px">
        <downLoadComponents
          ref="downLoadComponents"
          :formData="exportData"
          :apiUrl="downUrl"
          :fileText="fileText + '.xls'"
        >
          <a-button class="exportBtn" @click="onExport"> 导出数据 </a-button>
        </downLoadComponents>
      </div>
      <!-- 表格展示 -->
      <div class="table-page-content">
        <custom-table
          ref="table"
          rowKey="id"
          :showColSettings="true"
          :hideColSettings="['action']"
          :showAlert="false"
          :showSelection="true"
          :loading="loading"
          :columns="columns"
          :dataSource="pageData"
          @selectedRow="onSelectedRow"
          @change="onTableChange"
        >
          <template v-slot:colSettings>
            <a-button class="table-custom-cols"> 字段配置 </a-button>
          </template>
          <template slot="userName" slot-scope="text, record">
            <div class="userNameBox">
              <img
                v-if="record.userHeadUrl == null"
                src="~@/assets/icon/u18916.png"
                style="width: 40px; height: 40px; border-radius: 50%"
                alt=""
              />
              <img
                v-else
                :src="'data:image/png;base64,' + record.userHeadUrl"
                preview="1"
                style="width: 40px; height: 40px; border-radius: 50%; cursor: pointer"
              />
              <span>{{ text }}</span>
            </div>
          </template>
          <!--操作-->
          <template slot="action" slot-scope="text, record">
            <a-button @click="onDetails(record)" type="link" style="padding: 0">详情</a-button>
          </template>
        </custom-table>
      </div>
    </a-card>
  </div>
</template>

<script>
import moment from 'moment'
import * as informationApi from '@/api/information.js'
import { getQueryConfig, saveQueryConfig } from '@/api/alarm.js'
import { getXzqhList, getDictItemsFromCache } from '@/api/api'
import CustomTable from '@/components/zxd/Table/CustomTable'
import downLoadComponents from '@/components/zxd/downLoad'
export default {
  components: {
    CustomTable,
    downLoadComponents,
  },
  data() {
    return {
      moment,
      labelCol: { span: 5 },
      wrapperCol: { span: 18 },
      rangePickerTime: [],
      show: false,
      loading: false,
      visible: false,
      indeterminateState: false,
      reloading: false,
      dictOptions: getDictItemsFromCache('dataSource'), //劝阻状态-字典值
      selectKeys: [],
      formData: {},
      options: [
        { value: '2', text: '今天' },
        { value: '3', text: '近三天' },
        { value: '4', text: '近七天' },
        { value: '0', text: '自定义' },
      ],
      columns: [
        {
          title: '排行',
          dataIndex: 'order',
          width: 80,
          align: 'center',
          customRender: (text, record, index) =>
            `${(this.pageFilter.pageNo - 1) * this.pageFilter.pageSize + (index + 1)}`, //序号分页后连续
        },
        {
          title: '账户名',
          dataIndex: 'userName',
          width: 300,
          align: 'center',
          scopedSlots: { customRender: 'userName' },
        },
        {
          title: '疑似走私发布数',
          dataIndex: 'infoNum',
          // width: 115,
          align: 'center',
          scopedSlots: { customRender: 'infoNum' },
        },
        {
          title: '走私金额总数（万）',
          dataIndex: 'totalAmount',
          // width: 115,
          align: 'center',
          scopedSlots: { customRender: 'totalAmount' },
        },
        {
          title: '数据来源',
          dataIndex: 'userSourceType',
          // width: 115,
          align: 'center',
          scopedSlots: { customRender: 'userSourceType' },
        },
        {
          title: '更新时间',
          dataIndex: 'updateTime',
          width: 180,
          align: 'center',
          // customRender: (text) => {
          //   return text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : ''
          // },
        },
        {
          title: '操作',
          width: 80,
          align: 'center',
          dataIndex: 'action',
          // slots: { title: 'customIsAction' },
          scopedSlots: { customRender: 'action' },
        },
      ],
      pageFilter: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData: [],
      exportData: {},
      fileText: '走私排行-导出',
      downUrl: 'smuggle/smuUser/exportXls',
    }
  },
  computed: {
    checkAllState() {
      let bool = false
      let sourceTypeList =
        Object.keys(this.formData).length > 0 && this.formData.sourceTypeList
          ? this.formData.sourceTypeList.split(',')
          : []
      if (this.dictOptions.length === sourceTypeList.length) {
        bool = true
      }
      return bool
    },
  },
  created() {},
  async mounted() {
    await this.getConfig()
    // this.initForm()
    this.onQuery()
  },
  methods: {
    initForm() {
      this.$set(this.formData, 'timeType', this.options[0].value)
      this.$set(
        this.formData,
        'sourceTypeList',
        this.dictOptions
          .map((v) => {
            return v.value
          })
          .join(',')
      )
    },
    onQuery() {
      this.pageFilter.pageNo = 1
      this.refreshTable()
    },
    onResetForm() {
      this.formData = {}
      this.pageFilter.pageNo = 1
      this.pageFilter.pageSize = 10
      this.$nextTick(() => {
        // 重置行政区划
        // this.$refs.linkage.reload()
        this.reload()
      })
      this.initForm()
      this.refreshTable()
    },
    onSelectedRow(keys) {
      this.selectKeys = keys
    },
    onTableChange(pagination, pageFilter, sorter) {
      let keyMap = { currentPage: 'pageNo' }
      let paginations = Object.keys(pagination).reduce((newData, key) => {
        let newKey = keyMap[key] || key
        newData[newKey] = pagination[key]
        return newData
      }, {})
      this.pageFilter = Object.assign({}, this.pageFilter, paginations)
      this.refreshTable()
    },
    refreshTable(params) {
      if (params != undefined) {
        this.pageFilter.pageNo = params.currentPage
        this.pageFilter.pageSize = params.pageSize
      }
      // console.log(this.formData.sourceTypeList)
      if (this.formData.sourceTypeList != null && this.formData.sourceTypeList.length > 0) {
        this.pageFilter.sourceTypeList = this.formData.sourceTypeList.split(',')
      } else {
        this.pageFilter.sourceTypeList = []
      }
      let formData = Object.assign({}, this.formData, this.pageFilter)
      this.loading = true
      informationApi
        .smuUserList(formData)
        .then((res) => {
          if (res.success) {
            this.pageData = res.result
            this.loading = false
          } else {
            this.loading = false
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    //导出
    onExport() {
      if (this.formData.sourceTypeList != null && this.formData.sourceTypeList.length > 0) {
        this.pageFilter.sourceTypeList = this.formData.sourceTypeList.split(',')
      } else {
        this.pageFilter.sourceTypeList = []
      }
      this.exportData = Object.assign({}, this.formData, this.pageFilter)
      setTimeout(() => {
        this.exportData.idList = this.selectKeys
        this.$refs.downLoadComponents.exportDowmPOST()
        this.$refs.table.onClearRowKeys()
      }, 500)
    },
    // 保存配置
    saveConfig() {
      let obj = {
        sourceTypeList: this.formData.sourceTypeList,
        userName: this.formData.userName,
        publishedType: this.formData.publishedType,
        timeType: this.formData.timeType,
        beginTime: this.formData.beginTime,
        endTime: this.formData.endTime,
      }
      var parameter = {
        config: JSON.stringify(obj),
        modulePrefix: 'rankList',
      }
      saveQueryConfig(parameter)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message)
          } else {
            this.$message.warn(res.message)
          }
        })
        .catch((e) => {
          this.$message.warn('请求失败！')
        })
    },
    // 获取保存配置
    async getConfig() {
      // try {
      var parameter = {
        modulePrefix: 'rankList',
      }
      let res = await getQueryConfig(parameter)
      if (res.success) {
        let data = res.result && res.result != 'null' ? res.result : {}
        let parseData = Object.keys(data).length > 0 ? JSON.parse(data) : {}
        if (data && Object.keys(parseData).length > 0) {
          this.$set(this.formData, 'sourceTypeList', parseData.sourceTypeList)
          this.$set(this.formData, 'userName', parseData.userName)
          this.$set(this.formData, 'publishedType', parseData.publishedType)
          this.$set(this.formData, 'timeType', parseData.timeType)
          this.$set(this.formData, 'beginTime', parseData.beginTime)
          this.$set(this.formData, 'endTime', parseData.endTime)
          this.rangePickerTime = [parseData.beginTime, parseData.endTime]
        } else {
          this.initForm()
        }
      } else {
        this.initForm()
      }
    },
    // 详情
    onDetails(record) {
      this.$router.push({
        path: '/smuggleInformation/rankDetail',
        query: {
          id: record.id,
        },
      })
    },
    // 预警时间
    rangePickerChange(date) {
      this.$set(this.formData, 'beginTime', date[0])
      this.$set(this.formData, 'endTime', date[1])
    },
    onCheckAllChange(e) {
      Object.assign(this, { indeterminateState: false })
      this.$set(
        this.formData,
        'sourceTypeList',
        e.target.checked
          ? this.dictOptions
              .map((v) => {
                return v.value
              })
              .join(',')
          : null
      )
    },
    onChange(checkedList, type) {
      let dataLists = checkedList.split(',')
      this.indeterminateState = !!dataLists.length && dataLists.length < this.dictOptions.length
    },
    /** 重新加载组件 */
    reload() {
      this.reloading = true
      this.$nextTick(() => (this.reloading = false))
    },
  },
}
</script>
<style lang="less" scoped>
.mode_item {
  display: flex;
  border-bottom: 1px #dadada dashed;
  > div {
    flex: 0 0 40%;
  }
  & > * {
    width: 100%;
    margin-bottom: 0;
    padding: 5px 0;
  }
  &.mode_item_none {
    > div {
      flex: inherit;
    }
  }
  .zdy-form-item-label {
    /deep/.ant-form-item-label {
      width: 70px;
    }
    &.xzqh-form-item-label {
      /deep/.ant-form-item-control-wrapper {
        .ant-form-item-children {
          display: -webkit-box;
        }
      }
      /deep/.area-select {
        // margin-top: 4px;
        line-height: 1;
      }
      /deep/.select-tag {
        width: 162px !important;
        margin-left: 10px;
        margin-top: 3px;
      }
    }
  }
}
.search-wrapper-btn {
  position: absolute;
  right: 0;
  top: 15px;
  z-index: 1;
}
/deep/.table-custom-cols {
  top: -48px !important;
}
.custom-ewm {
  padding: 14px;
  background-color: #fff;
  border: 1px #ccc solid;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
}
/deep/.userNameBox {
  margin-left: 10%;
  display: flex;
  /* 设置侧轴居中 */
  align-items: center;
  span {
    margin-left: 20px;
  }
}
.modalImg {
  width: 650px;
}
</style>
